react-router4.0 路由传参跳转及获取参数

react-router4.0 路由传参跳转及获取参数

路由的跳转,传参分别是通过路由的三个属性history,location,match来进行的,可通过从最上层的路由props传至组件中,也可以通过以下形式获取

1
2
import {withRouter} from 'react-router-dom'
export default withRouter(Index)

这样Index组件的props就可以拿到这三个属性了

传参跳转history

params

  1. 需要现在路由表中配置
    1
    2
    3
    	<Route path="/:id">
    ```
    2. 通过`history.push`进行跳转

history.push(‘/123’); //或者
history.push({pathname: ‘/123’});


1
2
3
4
3. history 属性中还有一些其他的方法,此处不提。其他文档中都可以查到

### query
1. 通过`history.push`进行跳转

history.push({pathname: ‘/‘, search=”?page=1”});


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

## 获取参数
### params `match`
- params 获取参数是通过`match` 获取参数
- `match.params.xxx`

### query `location`
- query 获取参数是通过`location`获取参数
- `location.search`获取到`?page=1`字符串
- `yarn add query-string`
- `queryString.parse(location.search);`
- 就可以将参数转换成对象

还有种跳转是 state
1. 通过`history.push`进行跳转

history.push({pathname: ‘/‘, state={page:1}});
`

本文标题:react-router4.0 路由传参跳转及获取参数

文章作者:zzsnowstorm

发布时间:2019年04月15日 - 23:04

最后更新:2019年04月15日 - 15:04

原始链接:https://zzsnowstorm.github.io/react-router 4.0 路由传参跳转及获取参数/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

坚持原创技术分享,您的支持将鼓励我继续创作!